package com.gitee.feizns.quickstart.web.converter;

import com.gitee.feizns.dynamic.DateUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.lang.NonNull;

import java.sql.Time;
import java.sql.Timestamp;
import java.time.temporal.TemporalAccessor;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 日期转换器工厂
 * <p>
 *     添加对日期类型{@link TemporalAccessor}
 * </p>
 * @see ConverterFactory
 * @see DateUtils
 * @author feizns
 * @since 2023/2/3
 */
public class ToDateConverterFactory implements ConverterFactory<String, Date> {

    @Override
    public @NonNull <T extends Date> Converter<String, T> getConverter(@NonNull Class<T> targetType) {
        return source -> DateUtils.parse(source, targetType);
    }

    /**
     * java util日期转换器
     */
    public static final Converter<String, Date> JavaUtilDateConverter = new Converter<String, Date>() {
        @Override
        public Date convert(@NonNull String source) {
            return DateUtils.parse(source, Date.class);
        }
    };

    /**
     * java sql日期转换器
     */
    public static final Converter<String, java.sql.Date> JavaSqlDateConverter = new Converter<String, java.sql.Date>() {
        @Override
        public java.sql.Date convert(@NonNull String source) {
            return DateUtils.parse(source, java.sql.Date.class);
        }
    };

    /**
     * java sql时间转换器
     */
    public static final Converter<String, java.sql.Time> JavaSqlTimeConverter = new Converter<String, Time>() {
        @Override
        public Time convert(@NonNull String source) {
            return DateUtils.parse(source, java.sql.Time.class);
        }
    };

    /**
     * java sql时间戳转换器
     */
    public static final Converter<String, java.sql.Timestamp> JavaSqlTimestampConverter = new Converter<String, Timestamp>() {
        @Override
        public Timestamp convert(@NonNull String source) {
            return DateUtils.parse(source, java.sql.Timestamp.class);
        }
    };

    /**
     * 时间转换器
     * @return {@link List}<{@link Converter}<{@link String}, {@link ?} {@link extends} {@link Date}>>
     */
    public static List<Converter<String, ? extends Date>> dateConverters() {
        return Arrays.asList(
                JavaUtilDateConverter,
                JavaSqlDateConverter,
                JavaSqlTimeConverter,
                JavaSqlTimestampConverter
        );
    }

}
